package com.huiminpay.merchant.controller;


import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BizException;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.convert.AppConvert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.service.IAppService;
import com.huiminpay.merchant.vo.AppVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wsk
 * @since 2021-06-07
 */
@Slf4j
@RestController
@Api(value = "应用操作相关", tags = "应用操作相关", description = "应用操作相关1")
public class AppController {

    @Reference
    public IAppService appService;

    //@ApiOperation(value = "通过id查询应用")
    //@GetMapping("/my/apps/")
    //public AppVo findMerchantById(@PathVariable Long id) {
    //
    //
    //    AppDTO appDto = appService.findAppById(id);
    //    AppVo appVo = new AppVo();
    //    BeanUtils.copyProperties(appDto, appVo);
    //    return appVo;
    //}

    @ApiOperation(value = "创建应用")
    @PostMapping("/my/apps")
    public AppDTO createApp(@RequestBody AppVo appVo) {

//        1.非空校验

        if (StringUtil.isEmpty(appVo.getAppName())) {
            throw new BizException(CommonErrorCode.E_100005);
        }

//        2.保存数据库

        Long merchantId = SecurityUtil.getMerchantId();
        appVo.setMerchantId(merchantId);
        return appService.createApp(AppConvert.INSTANCE.vo2dto(appVo));
    }

    @ApiOperation(value = "查询我的应用")
    @GetMapping("/my/apps")
    public List<AppDTO> queryApps() {

        Long merchantId = SecurityUtil.getMerchantId();
        List<AppDTO> appDTOS = appService.queryApps(merchantId);

        return appDTOS;

    }

    @ApiOperation(value = "修改我的应用")
    @PutMapping("/my/apps")
    public AppDTO updateApp(@RequestBody AppVo appVo) {
//        1.非空校验
        if (StringUtil.isEmpty(appVo.getAppName())) {
            throw new BizException(CommonErrorCode.E_100005);
        }
        if (StringUtil.isEmpty(appVo.getAppId())) {
            throw new BizException(CommonErrorCode.E_100007);
        }

//        2.更新数据库

        return appService.updateApp(AppConvert.INSTANCE.vo2dto(appVo));


    }
}
